﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;

namespace PrestigeViewer
{
	public class WebDownload : WebClient
	{
		private int _timeout;
		/// <summary>
		/// 超时时间(毫秒)
		/// </summary>
		public int Timeout
		{
			get
			{
				return _timeout;
			}
			set
			{
				_timeout = value;
			}
		}

		public WebDownload()
		{
			this._timeout = 60000;
		}

		public WebDownload(int timeout)
		{
			this._timeout = timeout;
		}

		protected override WebRequest GetWebRequest(System.Uri address)
		{
			var result = base.GetWebRequest(address);
			result.Timeout = this._timeout;
			return result;
		}
	}
	class Helper
	{
		public static string GetSourceString(string url)
		{
			try
			{
				return Encoding.UTF8.GetString(new WebDownload().DownloadData(url));
			} catch
			{
				return "";
			}
		}

		public static string SearchString(string input, string regex)
		{
			return SearchString(input, new Regex(regex, RegexOptions.Singleline));
		}
		public static string SearchString(string input, Regex regex)
		{
			Match match = regex.Match(input);
			return match.Success ? match.Groups[1].Value : "";
		}

		public static List<string> SearchStrings(string input, string regex)
		{
			return SearchStrings(input, new Regex(regex, RegexOptions.Singleline));
		}
		public static List<string> SearchStrings(string input, Regex regex)
		{
			List<string> list =  new List<string>();

			Match match = regex.Match(input);

			while (match.Success)
			{
				list.Add(match.Groups[1].Value);
				match = match.NextMatch();
			}

			return list;
		}

		[DllImport("user32.dll")] //闪烁窗体
		public static extern bool FlashWindowEx(ref FLASHWINFO pwfi);

		[StructLayout(LayoutKind.Sequential)]
		public struct FLASHWINFO
		{
			public UInt32 cbSize;
			public IntPtr hwnd;
			public UInt32 dwFlags;
			public UInt32 uCount;
			public UInt32 dwTimeout;
		}
		//闪烁窗体参数
		public const UInt32 FLASHW_STOP = 0;//停止闪动.系统将窗体恢复到初始状态.
		public const UInt32 FLASHW_CAPTION = 1;//闪动窗体的标题.
		public const UInt32 FLASHW_TRAY = 2;//闪动任务栏按钮
		public const UInt32 FLASHW_ALL = 3;//闪动窗体标题和任务栏按钮
		public const UInt32 FLASHW_TIMER = 4;//连续不停的闪动,直到此参数被设置为:FLASHW_STOP
		public const UInt32 FLASHW_TIMERNOFG = 12;//连续不停的闪动,直到窗体用户被激活.通常用法将参数设置为: FLASHW_ALL | FLASHW_TIMERNOFG

		public static void FlashWindow(IntPtr handle)
		{
			FLASHWINFO fInfo = new FLASHWINFO
			{
				hwnd = handle,
				dwFlags = FLASHW_ALL | FLASHW_TIMERNOFG,
				uCount = UInt32.MaxValue,
				dwTimeout = 0
			};
			fInfo.cbSize = Convert.ToUInt32(System.Runtime.InteropServices.Marshal.SizeOf(fInfo));

			FlashWindowEx(ref fInfo);
		}
	}
}
